//
//  AddViewController.m
//  evidenceGather
//
//  Created by sampson on 13-8-25.
//  Copyright (c) 2013年 无. All rights reserved.
//

#import "AddViewController.h"

#import "UITableView+DataSourceBlocks.h"
#import "TableViewWithBlock.h"
#import "ZipArchive.h" 
#import "KTPhotoScrollViewController.h"
#import "PhotoDataSource.h"
#import "audio2Mp3.h"

#import "SelectionCell.h"
#import "Combox.h"
#import "Radio.h"

#import "TokDocManageUtilities.h"
#import "SystemUtils.h"
#import "Constants.h"

#import "UserVO.h"
#import "ProviceVO.h"

#import "GatherResult.h"
#import "ProblemClassVO.h"
#import "MDGather.h"
#import "MDProject.h"
#import "MDProbCls.h"
#import "MDProvince.h"
#import "DefButton.h"
#import "ASIFormDataRequest.h"

#import "FPPopoverController.h"
 
#import "ProjPoverProjViewController.h"
#import "YIPopupTextView.h"
#import "LoadingView.h"
#import "LocationManager.h"


@interface AddViewController ()

-(void) saveRecordFile:(UIImage *) image projCode:(NSString *) selectProjCode clsCode:(NSString *) selectClsCode fileType:(int) fileType;
-(void) addImage2View:(UIImage *) image;
-(void) saveRadio;

@end

@implementation AddViewController

@synthesize popoverController;
@synthesize userVO = _userVO;
@synthesize photoView=_photoView;
@synthesize radioView=_radioView;
@synthesize selectProvCode = _selectProvCode;
@synthesize selectProjCode = _selectProjCode;
@synthesize selectProjName = _selectProjName;
@synthesize selectClsCode = _selectClsCode;
@synthesize gathercode = _gathercode;
@synthesize imageCount = _imageCount;
@synthesize radioCount = _radioCount;
@synthesize radioFilePath = _radioFilePath;
@synthesize avPlay = _avPlay;

@synthesize mdProbCls = _mdProbCls;
@synthesize mdProject = _mdProject;
@synthesize mdGather = _mdGather;
@synthesize mdProvince = _mdProvince;

@synthesize probClsKeyValue = _probClsKeyValue;
@synthesize projKeyKeyValue = _projKeyKeyValue;
@synthesize probClsVOs = _probClsVOs;
@synthesize popoverCtrl = _popoverCtrl;
@synthesize clsWSMemo = _clsWSMemo;

 

@synthesize photos = _photos;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
//添加分类，知识点或者错题
-(void) addCateGoryInfo:(NSString *) groupName{
    NSMutableDictionary *probClsDict=[_mdProbCls qryProClsByPkUser:[_userVO loginuser]];
    NSArray *tempProbClsVOs=[probClsDict allValues];
    _probClsVOs=[[NSMutableArray alloc] init];
    for(int j=0;j<[probClsDict count];j++){
        ProblemClassVO *probClsVO = [tempProbClsVOs objectAtIndex:j];
        [_probClsVOs addObject:probClsVO];
        Radio *radio = [[Radio alloc] initWithGroupId:groupName index:j];
        int radioY=j*40-5;
        radio.frame = CGRectMake(150,radioY+5,26,26);
        
        if(j==0){
            [radio setChecked:YES];
            _selectClsCode=probClsVO.pccode;
        }
        
         
        UILabel *label11 =[[UILabel alloc] initWithFrame:CGRectMake(185, radioY, 560, 30)];
        label11.backgroundColor = [UIColor clearColor];
        label11.text = probClsVO.pcname;
        label11.font=[UIFont boldSystemFontOfSize:26];
        [radioContainer addSubview:label11];
        [radioContainer addSubview:radio];
        [label11 release];
        [radio release];
        
        DefButton *btn11 =[[DefButton alloc] initWithFrame:CGRectMake(550, radioY, 60, 30)];
        [btn11 setTitle:@"说明" forState:UIControlStateNormal];
        [btn11 addTarget:self action:@selector(addProdMemo:) forControlEvents:UIControlEventTouchUpInside];
        [btn11 setBtnCode:probClsVO.pccode];
        btn11.titleLabel.font=[UIFont boldSystemFontOfSize:26];
        [radioContainer addSubview:btn11];
        [btn11 release];
        [Radio addObserverForGroupId:groupName observer:self];
    }
}

//添加备注按钮
- (void)addProdMemo:(UIButton *)button{
    if(_selectProjCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择项目项目" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    
    DefButton * btn=(DefButton*)button;
    self.selectClsCode=btn.btnCode;
    
    YIPopupTextView* popupTextView = [[YIPopupTextView alloc] initWithPlaceHolder:@"请输入备注" maxCount:300];
    popupTextView.delegate = self;
    if(_clsWSMemo!=nil){ 
        popupTextView.text = [_clsWSMemo objectForKey:btn.btnCode];
    }
    
    [popupTextView showInView:self.view];
    
}


#pragma mark YIPopupTextViewDelegate

- (void)popupTextView:(YIPopupTextView *)textView willDismissWithText:(NSString *)text{
    
    if(_clsWSMemo==nil){
        _clsWSMemo=[[NSMutableDictionary alloc] init];
    }
    if(text!=nil && ![text isEqualToString:@""]){
        [_clsWSMemo setObject:text forKey:_selectClsCode];
        
        NSString *saveFilePath = [TokDocManageUtilities getFileDocPath];
        saveFilePath = [saveFilePath stringByAppendingPathComponent:_userVO.loginuser];
        saveFilePath = [saveFilePath stringByAppendingPathComponent:_selectProjCode];
        saveFilePath = [saveFilePath stringByAppendingString:@"_"];
        saveFilePath = [saveFilePath stringByAppendingString:_selectProjName];
        saveFilePath = [saveFilePath stringByAppendingPathComponent:_userVO.loginuser];
        saveFilePath = [saveFilePath stringByAppendingPathComponent:_selectClsCode];
        GatherResult *gatherReusltVO=[_mdGather qryUnCommitGatherInfo:_selectClsCode projCode:_selectProjCode prvcode:self.selectProvCode loginUser:_userVO.loginuser ];
        if(gatherReusltVO!=nil){
            _gathercode=gatherReusltVO.gathercode;
        }else{
            _gathercode=nil;
        }
        if(_gathercode==nil){
            GatherResult *gatherResultVO=[[GatherResult alloc] init];
            [gatherResultVO setIscommit:0];
            [gatherResultVO setLoginuser:_userVO.loginuser];
            [gatherResultVO setPccode:_selectClsCode];
            [gatherResultVO setProjcode:_selectProjCode];
            [gatherResultVO setProvcode:_selectProvCode];
            if(_clsWSMemo!=nil){
                NSString * memo=[_clsWSMemo objectForKey:_selectClsCode];
                [gatherResultVO setRemark:memo];
            }
            _gathercode=[_mdGather insertGatherRecord:gatherResultVO];
        }else{
            NSString * memo=[_clsWSMemo objectForKey:_selectClsCode];
            [_mdGather updateResultMemo:memo gatherRecord:_gathercode];
        }
        saveFilePath = [saveFilePath stringByAppendingPathComponent:_gathercode];
        NSString *memoPath = [saveFilePath stringByAppendingPathComponent:@"memo.txt"];
        [TokDocManageUtilities createFilePath:saveFilePath];
        NSData* fileMemo = [text dataUsingEncoding: NSASCIIStringEncoding];
        //将其他数据添加到缓冲中
        //将缓冲的数据写入到文件中
        [fileMemo writeToFile:memoPath atomically:YES];
    }
}

- (void)popupTextView:(YIPopupTextView *)textView didDismissWithText:(NSString *)text{
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //初始化信息
    if(_mdProject==nil){
        _mdProject=[[MDProject alloc] init];
    }
    if(_mdProbCls==nil){
        _mdProbCls=[[MDProbCls alloc] init];
    }
    
    if(_mdGather==nil){
        _mdGather=[[MDGather alloc] init];
    }
    
    if(_mdProvince==nil){
        _mdProvince=[[MDProvince alloc] init];
    }
    
    LocationManager *location=[[LocationManager alloc] init];
    //省份信息 
    self.selectProvCode = location.provCode;
    if(self.selectProvCode!=nil){
        ProviceVO *curProviceVO=[_mdProvince qryProvinceByPk:_selectProvCode];
        if(curProviceVO!=nil){ 
            [self provinceTextArea].text=[NSString stringWithFormat:@"%@_%@",_selectProvCode,curProviceVO.prvname];
        }
    }else{
        self.selectProvCode=@"01";
    }
    radioContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 270, 768, 320)];
    [self addCateGoryInfo:@"probCls"];
     
    [self.view addSubview:radioContainer];
    
    //图片文件视图
    CGRect photoFrame = CGRectMake(150, 588, 618, 150);
    _photoView = [ [UIScrollView alloc ] initWithFrame:photoFrame ];
    _photoView.contentSize = CGSizeMake(4800,150);
    _photoView.alwaysBounceHorizontal=NO;
    _photoView.pagingEnabled = YES;
    [self.view addSubview:_photoView];
    
    //视频文件视图
    CGRect frame = CGRectMake(150, 795, 618, 150);
    _radioView = [ [UIScrollView alloc ] initWithFrame:frame ];
    _radioView.contentSize = CGSizeMake(2400,150);
    _radioView.alwaysBounceHorizontal=NO;
    _radioView.pagingEnabled = YES;
    [self.view addSubview:_radioView];
}

 
- (void)viewDidAppear:(BOOL)animated {
    
    self.voiceHud = [[POVoiceHUD alloc] initWithParentView:self.view];
    self.voiceHud.title = @"点击空白已取消录音";
    
    [self.voiceHud setDelegate:self];
    [self.view addSubview:self.voiceHud];
}

- (IBAction)takePhotoBtn:(id)sender {
    if(_selectProjCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择项目项目" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    
    //真机测试时，打开此处代码，注释掉上面代码
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }else {
        //NSLog(@"模拟其中无法打开照相机");
        UIImage *image =[UIImage imageNamed:@"photo3l.jpg"];
        //设置图片为背景
        // UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        [self saveRecordFile:image projCode:_selectProjCode clsCode:_selectClsCode fileType:1];
    }
    
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        //设置图片为背景
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        [picker dismissModalViewControllerAnimated:YES];
        [self saveRecordFile:image projCode:_selectProjCode clsCode:_selectClsCode fileType:1];
    }
}

//图片保存
-(void) saveRecordFile:(UIImage *) image projCode:(NSString *) selProjCode clsCode:(NSString *) selClsCode fileType:(int)fileType{
    GatherResult *gatherReusltVO=[_mdGather qryUnCommitGatherInfo:_selectClsCode projCode:_selectProjCode prvcode:self.selectProvCode loginUser:_userVO.loginuser ];
    if(gatherReusltVO!=nil){
        _gathercode=gatherReusltVO.gathercode;
    }else{
        _gathercode=nil;
    }
    if(_gathercode==nil){
        GatherResult *gatherResultVO=[[GatherResult alloc] init];
        [gatherResultVO setIscommit:0];
        [gatherResultVO setLoginuser:_userVO.loginuser];
        [gatherResultVO setPccode:selClsCode];
        [gatherResultVO setProjcode:selProjCode];
        [gatherResultVO setProvcode:_selectProvCode];
        if(_clsWSMemo!=nil){
            NSString * memo=[_clsWSMemo objectForKey:_selectClsCode];
            [gatherResultVO setRemark:memo]; 
        }
       
        _gathercode=[_mdGather insertGatherRecord:gatherResultVO];
    }
    NSString *saveFilePath = [TokDocManageUtilities getFileDocPath];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:[_userVO loginuser]];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:selProjCode];
    saveFilePath = [saveFilePath stringByAppendingString:@"_"];
    saveFilePath = [saveFilePath stringByAppendingString:_selectProjName];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:[_userVO loginuser]];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:selClsCode];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:_gathercode];
    if(fileType==1){
        saveFilePath = [saveFilePath stringByAppendingPathComponent:@"picture"];
    }else{
        saveFilePath = [saveFilePath stringByAppendingPathComponent:@"radio"];
    }
  
    [TokDocManageUtilities createFilePath:saveFilePath];
    NSString *fileName=[TokDocManageUtilities getFileName:selProjCode andWithFile:selClsCode];
    NSString *fullPath = [saveFilePath stringByAppendingPathComponent:fileName];
    GatherFileVO *gatherFileVO=[[GatherFileVO alloc] init];
    [gatherFileVO setFilename:fileName];
    [gatherFileVO setGathercode:_gathercode];
    [gatherFileVO setFiletype:fileType];
    [gatherFileVO setFilepath:fullPath];
    NSString *curTime=[SystemUtils getCurTime];
    [gatherFileVO setGathertime:curTime];
    if(fileType==1){
        fullPath = [fullPath stringByAppendingString:@".png"];
        [UIImagePNGRepresentation(image)writeToFile: fullPath atomically:YES];
        [gatherFileVO setFilesuffix:@"png"];
    }else{
        fullPath = [fullPath stringByAppendingString:@".caf"];
        [gatherFileVO setFilesuffix:@"caf"];
    }
    [_mdGather insertGatherFile:gatherFileVO];
    [self addImage2View:image];
}


-(void) addImage2View:(UIImage *) image{
    
    float photoWidth=0.0f;
    //imageView宽度
    float width = 145.0f;
    //imageView高度
    float height = 110.0f;
    //列间距，即左右间隔
    float columnGap = 20.0f;
    float originalX=photoWidth+(width+columnGap)*_imageCount;
    float originaly=30.0f;
    DefButton  *imageButton = [[DefButton alloc] initWithFrame:CGRectMake(originalX,originaly, width, height)] ;
    [imageButton setImage:image forState:UIControlStateNormal];
    //为按钮添加UITouch事件
    [imageButton addTarget:self action:@selector(clickPhoto:) forControlEvents:UIControlEventTouchUpInside];
    imageButton.backgroundColor = [UIColor whiteColor];
    [_photoView addSubview:imageButton];
    [imageButton release];
     _imageCount=++_imageCount;
    float photoViewWidth=photoWidth+(width+columnGap)*_imageCount;
    _photoView.contentSize = CGSizeMake(photoViewWidth,150);
   
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
//    NSLog(@"您取消了选择图片");
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma mark - Radio Delegate

//radio选择事件
-(void)radioButtonSelectedAtIndex:(NSInteger *)index inGroup:(NSString*)groupId{
    if([groupId isEqualToString:@"probCls"]){
        ProblemClassVO *probClsVO = [_probClsVOs objectAtIndex:index];
//        当前选中问题分类编码
        _selectClsCode=probClsVO.pccode;
        if(_selectProjCode!=nil){
            GatherResult *gatherReusltVO=[_mdGather qryUnCommitGatherInfo:_selectClsCode projCode:_selectProjCode prvcode:self.selectProvCode loginUser:_userVO.loginuser ];
            [self afterRadioClick:gatherReusltVO];
        }else{
            UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择项目项目" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];
            return ;
        }
    }
}

-(void) afterRadioClick:(GatherResult *)gatherReusltVO{
    for(id tmpView in [_photoView subviews ]){
        //找到要删除的子视图的对象
        if([tmpView isKindOfClass:[DefButton class]]){
            DefButton *imgView = (DefButton *)tmpView;
            [imgView removeFromSuperview]; //删除子视图
        }
    }
    
    for(id tmpView in [_radioView subviews]){
        //找到要删除的子视图的对象
        if([tmpView isKindOfClass:[DefButton class]]){
            DefButton *imgView = (DefButton *)tmpView;
            [imgView removeFromSuperview]; //删除子视图
        }
    }
    
    if(gatherReusltVO!=nil){
        //将未提交的记录的主键付给当前记录编号
        _gathercode=gatherReusltVO.gathercode;
        if(_clsWSMemo==nil){
            _clsWSMemo=[[NSMutableDictionary alloc] init];
        }
        [_clsWSMemo setObject:gatherReusltVO.remark forKey:_selectClsCode];
        NSString *photoPath=[TokDocManageUtilities getFileDocPath];
        photoPath=[photoPath  stringByAppendingPathComponent:gatherReusltVO.loginuser];
        photoPath=[photoPath  stringByAppendingPathComponent:gatherReusltVO.projcode];
        photoPath = [photoPath stringByAppendingString:@"_"];
        photoPath = [photoPath stringByAppendingString:_selectProjName];
        photoPath = [photoPath stringByAppendingPathComponent:gatherReusltVO.loginuser];
        photoPath=[photoPath  stringByAppendingPathComponent:gatherReusltVO.pccode];
        photoPath=[photoPath  stringByAppendingPathComponent:gatherReusltVO.gathercode];
        
        //    NSLog(@"the photoPath is %@",photoPath);
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        NSError *error = nil;
        NSArray *fileList = [[NSArray alloc] init];
        
        
        //添加图片至图片区
        NSString *picturePath=[photoPath  stringByAppendingPathComponent:@"picture"];
        //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
        fileList = [fileManager contentsOfDirectoryAtPath:picturePath error:&error];
        int imageCount1=0;
        for(NSString *imageName in fileList){
            if([imageName hasSuffix:@"png"]){
                NSString *tempStr=[picturePath stringByAppendingPathComponent:imageName];
                NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath:tempStr traverseLink:NO];
                BOOL isDirectory=[[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
                if (!isDirectory) {
                    NSString *filePath=[picturePath stringByAppendingPathComponent:imageName];
                    NSData *myData=[fileManager contentsAtPath:filePath];
                    UIImage *myImage=[UIImage imageWithData:myData];
                    [self addImage2View:myImage imageCount:imageCount1 gatherCode:_selectClsCode];
                    imageCount1++;
                }
            }
        }
        
        //添加录音至录音区
        
        //添加图片至图片区
        NSString *radioPath=[photoPath  stringByAppendingPathComponent:@"radio"];
        //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
        fileList = [fileManager contentsOfDirectoryAtPath:radioPath error:&error];
        int radioCount1=0;
        for(NSString *radioName in fileList){
            if([radioName hasSuffix:@"caf"]){
                NSString *tempStr=[radioPath stringByAppendingPathComponent:radioName];
                NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath:tempStr traverseLink:NO];
                BOOL isDirectory=[[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
                if (!isDirectory) {
                    NSString *filePath=[radioPath stringByAppendingPathComponent:radioName];
                    [self addRadio2View:filePath radioCount:radioCount1];
                    radioCount1++;
                }
            }
        }
    }else{
        for(id tmpView in [ _photoView subviews ]){
            //找到要删除的子视图的对象
            if([tmpView isKindOfClass:[DefButton class]]){
                DefButton *imgView = (DefButton *)tmpView;
                [imgView removeFromSuperview]; //删除子视图
            }
        }
        
        
        for(id tmpView in [_radioView subviews]){
            //找到要删除的子视图的对象
            if([tmpView isKindOfClass:[DefButton class]]){
                DefButton *imgView = (DefButton *)tmpView;
                [imgView removeFromSuperview]; //删除子视图
            }
        }
        
    }
}


-(void) addImage2View:(UIImage *) image imageCount:(float) imageCount1 gatherCode:(NSString*)gatherCode{
    float photoWidth=0.0f;
    //imageView宽度
    float width = 145.0f;
    //imageView高度
    float height = 110.0f;
    //列间距，即左右间隔
    float columnGap = 10.0f;
    float originalX=photoWidth+(width+columnGap)*imageCount1;
    float originaly=30.0f;
    DefButton  *imageButton = [[DefButton alloc] initWithFrame:CGRectMake(originalX,originaly, width, height)] ;
    [imageButton setImage:image forState:UIControlStateNormal];
    //为按钮添加UITouch事件
    [imageButton addTarget:self action:@selector(clickPhoto:) forControlEvents:UIControlEventTouchUpInside];
    imageButton.backgroundColor = [UIColor whiteColor];
    [imageButton setBtnCode:gatherCode];
    [_photoView addSubview:imageButton];
    [imageButton release];
    _imageCount=++_imageCount;
    float photoViewWidth=photoWidth+(width+columnGap)*_imageCount;
    _photoView.contentSize = CGSizeMake(photoViewWidth,150);
    
}

-(void) addRadio2View:(NSString *)radioFilePath1 radioCount:(float)radioCount1{
    float photoWidth=0.0f;
    //imageView宽度
    float width = 145.0f;
    //imageView高度
    float height = 110.0f;
    //列间距，即左右间隔
    float columnGap = 10.0f;
    float originalX=photoWidth+(width+columnGap)*radioCount1;
    float originaly=30.0f;
    
    //先把图片转成NSData
    UIImage *image =[UIImage imageNamed:@"sound_btn.png"];
    //设置图片为背景
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    
    DefButton  *imageButton = [[DefButton alloc] initWithFrame:CGRectMake(originalX,originaly, width, height)] ;
    [imageButton setImage:image forState:UIControlStateNormal];
    [imageButton setBtnName:radioFilePath1];
    //为按钮添加UITouch事件
    [imageButton addTarget:self action:@selector(clickRadio:) forControlEvents:UIControlEventTouchUpInside];
    imageButton.backgroundColor = [UIColor whiteColor];
    [_radioView addSubview:imageButton];
    [imageButton release];
    _radioCount=++_radioCount;
    float photoViewWidth=photoWidth+(width+columnGap)*_radioCount;
    _radioView.contentSize = CGSizeMake(photoViewWidth,150);
}

#pragma mark - button Action 



//当触摸图片时，响应该方法
- (void)clickPhoto:(UIButton *)button{
    NSString *saveFilePath = [TokDocManageUtilities getFileDocPath];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:[_userVO loginuser]];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:_selectProjCode];
    saveFilePath = [saveFilePath stringByAppendingString:@"_"];
    saveFilePath = [saveFilePath stringByAppendingString:_selectProjName];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:[_userVO loginuser]];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:_selectClsCode];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:_gathercode];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:@"picture"];
    PhotoDataSource *dataSource_ = [[PhotoDataSource alloc] init:saveFilePath];
    KTPhotoScrollViewController *newController = [[KTPhotoScrollViewController alloc]
                                                  initWithDataSource:dataSource_
                                                  andStartWithPhotoAtIndex:index];
    [self presentModalViewController:newController animated:YES];
    [newController release];
}




- (IBAction)radioBtn:(id)sender {
    if(_selectProjCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择项目项目" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    GatherResult *gatherReusltVO=[_mdGather qryUnCommitGatherInfo:_selectClsCode projCode:_selectProjCode prvcode:self.selectProvCode loginUser:_userVO.loginuser ];
    if(gatherReusltVO!=nil){
        _gathercode=gatherReusltVO.gathercode;
    }else{
        _gathercode=nil;
    }
    if(_gathercode==nil){
        GatherResult *gatherResultVO=[[GatherResult alloc] init];
        [gatherResultVO setIscommit:0];
        [gatherResultVO setLoginuser:_userVO.loginuser];
        [gatherResultVO setPccode:_selectProjCode];
        [gatherResultVO setProjcode:_selectClsCode];
        [gatherResultVO setProvcode:_selectProvCode];
        if(_clsWSMemo!=nil){
            NSString * memo=[_clsWSMemo objectForKey:_selectClsCode];
            [gatherResultVO setRemark:memo];
        }
        _gathercode=[_mdGather insertGatherRecord:gatherResultVO];
    }

    
    NSString *saveFilePath = [TokDocManageUtilities getFileDocPath];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:[_userVO loginuser]];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:_selectProjCode];
    saveFilePath = [saveFilePath stringByAppendingString:@"_"];
    saveFilePath = [saveFilePath stringByAppendingString:_selectProjName];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:[_userVO loginuser]];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:_selectClsCode];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:_gathercode];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:@"radio"];
    
    [TokDocManageUtilities createFilePath:saveFilePath];
    NSString *fileName=[TokDocManageUtilities getFileName:_selectProjCode andWithFile:_selectClsCode];
    NSString *fullPath = [saveFilePath stringByAppendingPathComponent:fileName];
    fullPath = [fullPath stringByAppendingString:@".caf"];
    self.radioFilePath=fullPath;
    [self.voiceHud startForFilePath:[NSString stringWithFormat:fullPath, NSHomeDirectory()]];
    [self.radioBtn setUserInteractionEnabled:YES];
    [self.radioBtn setEnabled:FALSE];

}

#pragma mark - POVoiceHUD Delegate

//点击空白处，取消录音
- (void)POVoiceHUD:(POVoiceHUD *)voiceHUD voiceRecorded:(NSString *)recordPath length:(float)recordLength {
    NSLog(@"Sound recorded with file   seconds");
    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您已经取消了录音" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show]; 
    
    [self.radioBtn setUserInteractionEnabled:YES];
    [self.radioBtn setEnabled:TRUE];
}



//录音完毕
- (void)voiceRecordCancelledByUser:(POVoiceHUD *)voiceHUD {
    float photoWidth=0.0f;
    //imageView宽度
    float width = 145.0f;
    //imageView高度
    float height = 110.0f;
    //列间距，即左右间隔
    float columnGap = 10.0f;
    float originalX=photoWidth+(width+columnGap)*_radioCount;
    float originaly=20.0f;
    
    //先把图片转成NSData
    UIImage *image =[UIImage imageNamed:@"sound_btn.png"];
    //设置图片为背景
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    
    DefButton  *imageButton = [[DefButton alloc] initWithFrame:CGRectMake(originalX,originaly, width, height)] ;
    [imageButton setImage:image forState:UIControlStateNormal];
    [imageButton setBtnName:_radioFilePath];
    //为按钮添加UITouch事件
    [imageButton addTarget:self action:@selector(clickRadio:) forControlEvents:UIControlEventTouchUpInside];
    [imageButton setTitle:@"stsstst" forState:UIControlStateNormal];
    imageButton.backgroundColor = [UIColor whiteColor];
    [_radioView addSubview:imageButton];
    [imageButton release];
    _radioCount=++_radioCount;
    float photoViewWidth=photoWidth+(width+columnGap)*_radioCount;
    _radioView.contentSize = CGSizeMake(photoViewWidth,150);
    [self.radioBtn setUserInteractionEnabled:YES];
    [self.radioBtn setEnabled:TRUE];
}


//当触摸录音时，响应该方法
- (void)clickRadio:(UIButton *)button{
    DefButton* cls = (DefButton*)button; 
    NSURL *url = [NSURL fileURLWithPath:cls.btnName];
   
    if (self.avPlay.playing) {
        [self.avPlay stop];
    }
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.avPlay = player;
   
    [self.avPlay play];
     [player release];
}

-(int) zipFile{
    NSString *docPhotoPath = [TokDocManageUtilities getFileDocPath];
    //    docPhotoPath = [docPhotoPath stringByAppendingPathComponent:[userVO loginuser]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    int isZiped=2;
    BOOL isDir=NO;
    if ([fileManager fileExistsAtPath:docPhotoPath isDirectory:&isDir] && isDir){
        //获取所有项目文件夹名称
        NSArray *projPaths=[fileManager contentsOfDirectoryAtPath:docPhotoPath error:nil];
        
        for(NSString *projName in projPaths){
            NSString *longPath = [docPhotoPath stringByAppendingPathComponent:projName];
            if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && isDir){
                ZipArchive *archiver = [[ZipArchive alloc] init];
                
                //文件按照项目打包
                NSString *archivePath = [longPath stringByAppendingString:@".zip"];
                [archiver CreateZipFile2:archivePath];
                NSString *projFilePath=[docPhotoPath stringByAppendingPathComponent:projName];
                NSArray *subpaths = [fileManager subpathsAtPath:projFilePath];
                for(NSString *path in subpaths){
                    if(![path hasSuffix:@"DS_Store"]){
                        NSLog(@"longPath %@",path);
                        NSArray *values=[path componentsSeparatedByString:@"/"];
                        //截取路径长度，如果等于4，表明最后一级是记录主键
                        if([values count]>=4){
                            NSString *pkGather=[values objectAtIndex:3];
                            //如果记录未提交，则压缩文件，否则不做处理
                            if(![_mdGather isCommit:pkGather]){
                                isZiped=0;
                                NSString *longPath = [docPhotoPath stringByAppendingPathComponent:projName];
                                longPath = [longPath stringByAppendingPathComponent:path];
                                //NSLog(@"longPath %@",longPath);
                                //只打包具体文件，不打包文件夹
                                if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir){
                                    [archiver addFileToZip:longPath newname:path];
                                }
                            }
                        }
                    }
                }
                BOOL successCompressing = [archiver CloseZipFile2];
                if(successCompressing){
                    isZiped=0;
                }else{
                    isZiped=1;
                }
            }
        }
    }
    return isZiped;
}



-(BOOL) uploadFile{
    BOOL isuploaded=FALSE;
    //以下是文件上传
//    NSString *url=[NSString stringWithFormat:@"http://124.65.69.158:6002/UploadForIOS/upload.ashx"];
      NSString *url=[[NSString alloc]initWithFormat:@"http://%@:%@/upload.ashx",_userVO.serverIP,_userVO.serverPort];
    
    ASIFormDataRequest *form = [[[ASIFormDataRequest alloc]
                                 initWithURL:[NSURL URLWithString:url]] autorelease];
    [form setTimeOutSeconds:60.0];
    form.delegate = self;

    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    NSString *docPhotoPath = [TokDocManageUtilities getFileDocPath];
    NSString *file=[docPhotoPath stringByAppendingPathComponent:[_userVO loginuser]];
    file=[file stringByAppendingString:@".zip"];
//    NSLog(@"the upload file is :%@",file);
    NSData* data = [NSData dataWithContentsOfFile:file];;
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    [body appendFormat:@"Content-Disposition: form-data "];
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    [form setRequestMethod:@"POST"];
    NSString * fileName=[[NSString alloc]initWithFormat:@"%@.zip",_userVO.loginuser];

    [form setPostValue:fileName forKey:@"file"];
    [form setData:data forKey:@"file"];
    //            [form setUploadProgressDelegate:uploadProgress];
    [form setShowAccurateProgress:YES];
    [form setDelegate:self];
    [form startAsynchronous];
    NSError *error = [form error];
    if (!error) {
        NSString *response = [form responseString];
        NSLog(@"响应信息：%@",response);
        isuploaded=TRUE;
    }
    return isuploaded;
}

- (void)myTask {
	NSString *showMsg=nil;
    int isziped=[self zipFile];
    if(isziped==0){
        BOOL isupload=[self uploadFile];
        if(isupload){
            showMsg=@"采样记录上传成功";
            //更改项目下所有采样记录为提交态
            [_mdGather updateResultStatus:_selectProvCode projCode:_selectProjCode loginUser:_userVO.loginuser];
        }else{
            showMsg=@"采样记录上传失败";
        }
    }else if(isziped==1){
        showMsg=@"文件压缩失败";
    }else if(isziped==2){
        showMsg=@"没有需要提交的采样记录";
    }
    [loadingView removeFromSuperview];
}

//提交按钮
- (IBAction)cmtBtn:(id)sender {
    if(_selectProjCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择项目项目" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    loadingView = [LoadingView loadingViewInView:self.view title:@"正在上传采样记录，请稍后，提交完成后，对话框会自动消失。"];
	[loadingView showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

 
- (IBAction)closeBtn:(id)sender {
     [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    [_provinceTextArea release];
    [_projTextArea release];
    [_radioBtn release];
    [_projBtn release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setProvinceTextArea:nil];
    [self setProjTextArea:nil];
    [self setRadioBtn:nil];
    [self setProjBtn:nil];
    [super viewDidUnload];
}


- (IBAction)projBtnClick:(id)sender {
    if(_selectProvCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择省份" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    ProjPoverProjViewController *provView=[[ProjPoverProjViewController alloc] initViewWithCode:_selectProvCode];
    
    provView.delegate=self;
    
    FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:provView];
    [provView release];
    
    //popover.arrowDirection = FPPopoverArrowDirectionAny;
    popover.tint = FPPopoverDefaultTint;
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        popover.contentSize = CGSizeMake(300, 300);
    }
    popover.arrowDirection = FPPopoverArrowDirectionAny;
    
    //sender is the UIButton view
    [popover presentPopoverFromView:sender];
    _popoverCtrl=popover;
    
}


#pragma mark - PopoverViewSelectDelegate


- (void)afterCellSelected:(NSString *) cellCode cellName:(NSString *) cellName tag :(int) tag{
    
    [_popoverCtrl dismissPopoverAnimated:YES];
    NSString * cellTitle=cellCode;
    cellTitle=[cellTitle stringByAppendingString:@"_"];
    cellTitle=[cellTitle stringByAppendingString:cellName];
    if(tag==2){
        [self.projBtn setTitle:cellTitle forState:UIControlStateNormal];
        self.selectProjCode=cellCode;
        self.selectProjName=cellName;
    } 
}

@end
